package com.hongxiangly.ip.impl;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hongxiangly.ip.Address;
import com.hongxiangly.ip.IpAddress;
import com.hongxiangly.ip.exception.IpException;

import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@Slf4j
public class Ip2RegionImpl implements IpAddress {
	@Override
	public Address getAddress(String ip) throws IpException {
		String url = "https://ip.ffhome.top/ip/" + ip;
		Address address = new Address();
		address.setIp(ip);
		OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(8, TimeUnit.SECONDS)
				.readTimeout(15, TimeUnit.SECONDS).build();

		Request request = new Request.Builder().url(url)
				.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows 7)").get()
				.addHeader("Cache-Control", "no-cache").build();

		try {
			Response response = client.newCall(request).execute();
			if (response.isSuccessful()) {
				String result = response.body().string();
				log.debug("Ip2Region getAddress result:{},{}", url, result);
				JSONObject obj = JSON.parseObject(result);
				if (obj.getInteger("code") == 0) {
					address.setCountry(obj.getString("country"));
					address.setProvince(obj.getString("region"));
					address.setCity(obj.getString("city"));
					address.setOrganization(obj.getString("isp"));
				} else {
					throw new IpException("Ip2Region没有取到IP信息:" + ip);
				}
			}
		} catch (IOException e1) {
			throw new IpException("取信息出错:" + e1.getMessage());
		}
		return address;
	}
}
